package com.wyc.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.wyc.pojo.Result;
import com.wyc.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private JWTUtils jwtUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle....");
        //获取请求头的token
        String token = request.getHeader("token");
        boolean flag = StringUtils.hasLength(token);
        //如果token为空则返回error
        if(!flag){
            Result result = Result.error("token为空");
            String json_result=JSONObject.toJSONString(result);
            response.getWriter().write(json_result);
            return false;
        }
        //解析jwt
        try{
            jwtUtils.parse(token);
        }catch(Exception e){
            Result result = Result.error("token失败");
            String json_result=JSONObject.toJSONString(result);
            response.getWriter().write(json_result);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle....");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion....");
    }
}
